//% color="#599eff" iconWidth=50 iconHeight=40
namespace xunfei{
    //% block="讯飞语音识别音频 APPID[ID] APISecret[SECRET] APIKey[KEY] 待识别音频文件[FILE]" blockType="command" 
    //% ID.shadow="string"  ID.defl=" "
    //% SECRET.shadow="string"  SECRET.defl=" "
    //% KEY.shadow="string"  KEY.defl=" "
    //% FILE.shadow="string" FILE.defl="my.wav"
    export function xunfei_shibie(parameter: any, block: any) {
         let id = parameter.ID.code;  
         let secret = parameter.SECRET.code;
         let key = parameter.KEY.code;
         let file = parameter.FILE.code;
 
        Generator.addImport("import urequests");   
        Generator.addCode(`xunfei_params = {"APPID":${id}, "APISecret":${secret}, "APIKey":${key}}`);
        Generator.addCode(`_rsp = urequests.post("http://119.23.66.134:8085/xunfei_iat", files={"file":(${file}, "audio/wav")}, params=xunfei_params)`);
        Generator.addCode(`try:
    xunfei_iat_result = _rsp.json()
except:
    xunfei_iat_result = {"text":""}
        `);
        
   
    }

    //% block="讯飞语音合成音频 APPID[ID] APISecret[SECRET] APIKey[KEY] 文字内容[TXT] 转存为音频文件[FILE]" blockType="command" 
    //% ID.shadow="string"  ID.defl=" "
    //% SECRET.shadow="string"  SECRET.defl=" "
    //% KEY.shadow="string"  KEY.defl=" "
    //% TXT.shadow="string"  TXT.defl=" "
    //% FILE.shadow="string" FILE.defl="tts.pcm"
    export function xunfei_hecheng(parameter: any, block: any) {
        let id = parameter.ID.code;  
        let secret = parameter.SECRET.code;
        let key = parameter.KEY.code;
        let txt = parameter.TXT.code;
        let file = parameter.FILE.code;

       Generator.addImport("import urequests");   
       Generator.addCode(`speech_tts = {"APPID":${id}, "APIKey":${key}, "APISecret":${secret}, "filename":${file}, "text":${txt}}`);
       Generator.addCode(`rsp = urequests.post("http://119.23.66.134:8085/tts", params=speech_tts)`);
       Generator.addCode(`with open(${file}, "w") as _f:
    while True:
       dat = rsp.recv(4096)
       if not dat:
           break
       _f.write(dat)`);
       
  
   }

    //% block="讯飞语音 获取识别结果" blockType="reporter" 
    export function xunfei_jieguo(parameter: any, block: any) {
        Generator.addImport("import urequests"); 
        Generator.addCode(`xunfei_iat_result["text"]`);
                  
   }
   }
    